package com.hydl.power.utils;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;


public class AddressUtils {

    /**
     * 获取ip
     * @param request HttpServletRequest request
     * @return ip
     */
    public static String getIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }



    /**
     * 百度地图获取ip地址
     * @param ip ip
     * @return  IP地址
     */
    public static String getIpAddress(String ip){
        String url = "http://api.map.baidu.com/location/ip";
        Map params = new HashMap<>();
        String result = "";
        if(StringUtils.isNotBlank(ip)){
            params.put("ip",ip);
        }
        params.put("ak","iOepKtPRwl86iPOOoQ6OQGlfky34w5EG");
        params.put("output","JSON");
        String resultStr = HttpUtil.get(url, params);
        JSONObject jsonObject =JSONObject.parseObject(resultStr);
        if("0".equals(jsonObject.getString("status"))){
            JSONObject json = jsonObject.getJSONObject("content");
            result = json.getString("address");
        }else{
             result = getAddress(ip);
        }
        return result;
    }



    /**
     * 高德地图获取ip地址
     * @param ip ip
     * @return  IP地址
     */
    public static String getAddress(String ip){
        String url = "https://restapi.amap.com/v3/ip";
        Map params = new HashMap<>();
        String result = "";
        if(StringUtils.isNotBlank(ip)){
            params.put("ip",ip);
        }
        params.put("key","ced50db2180d582a2e56c35586fe8127");
        params.put("output","JSON");
        String resultStr = HttpUtil.get(url, params);
        JSONObject jsonObject = JSONObject.parseObject(resultStr);
        if("1".equals(jsonObject.getString("status"))){
            if(StringUtils.isNotBlank(jsonObject.getString("province")) && !"[]".equals(jsonObject.getString("province"))){
                result += jsonObject.getString("province");
            }
            if(StringUtils.isNotBlank(jsonObject.getString("city")) && !"[]".equals(jsonObject.getString("city"))){
                result += jsonObject.getString("city");
            }
        }else{
            result = "获取位置失败";
        }
        return  result;
    }



}
